#!/usr/bin/python3
import time
import serial

#print("UART Demonstration Program")
#print("NVIDIA Jetson Nano Developer Kit")


serial_port = serial.Serial(
    port="/dev/ttyTHS1",
    baudrate=115200,
    bytesize=serial.EIGHTBITS,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
)
# Wait a second to let the port initialize
time.sleep(1)
def get_uart_data():
    data=""
    while serial_port.inWaiting() > 0:
        read_data=serial_port.read()
        try:
            data = data + str(read_data,encoding="utf-8")
        except:
            serial_port.flushInput()
            data=""
            break
        finally:
            if read_data == "\n".encode():
                break
    #print(data)
    #serial_port.write(data.encode())
    return data

if __name__ == "__main__":
    try:
        # Send a simple header
        serial_port.write("UART Demonstration Program\r\n".encode())
        serial_port.write("NVIDIA Jetson Nano Developer Kit\r\n".encode())
        data=""
        while True:
            if serial_port.inWaiting() > 0:
                read_data=serial_port.read()
                data = data + str(read_data,encoding="utf-8")
                #serial_port.write(data)
                # if we get a carriage return, add a line feed too
                # \r is a carriage return; \n is a line feed
                # This is to help the tty program on the other end 
                # Windows is \r\n for carriage return, line feed
                # Macintosh and Linux use \n
                if read_data == "\n".encode():
                    print(data)
                    serial_port.write(data.encode())
                    data=""
                    # For Windows boxen on the other end


    except KeyboardInterrupt:
        print("Exiting Program")

    except Exception as exception_error:
        print("Error occurred. Exiting Program")
        print("Error: " + str(exception_error))

    finally:
        serial_port.close()
        
        pass
